package com.zwl.chengguangservice.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zwl.chengguangservice.dao.AppVersionMapper;
import com.zwl.chengguangservice.entity.AppVersion;
import com.zwl.chengguangservice.entity.Result;
import com.zwl.chengguangservice.pojo.CheckUpgradeDTO;
import com.zwl.chengguangservice.pojo.CreateVersionDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;

/** @date 2022/02/19 */
@RestController
@RequestMapping("/v1/version")
public class VersionController {
    @Resource private AppVersionMapper appVersionMapper;

    @PostMapping
    public Result<Boolean> createVersion(@RequestBody CreateVersionDTO createVersionDTO) {
        AppVersion appVersion1 =
                appVersionMapper.selectOne(
                        Wrappers.<AppVersion>lambdaQuery()
                                .eq(AppVersion::getAppType, createVersionDTO.getAppType())
                                .eq(
                                        AppVersion::getVersionNumber,
                                        createVersionDTO.getVersionNumber()));
        if (appVersion1 != null) {
            return new Result<>("版本号已经存在了", 500, null);
        }

        AppVersion appVersion = new AppVersion();
        BeanUtils.copyProperties(createVersionDTO, appVersion);
        appVersion.setReleaseTime(new Date());
        appVersionMapper.insert(appVersion);
        return new Result<>("版本创建成功", 200, true);
    }

    @PostMapping("check")
    public Result<AppVersion> checkUpgrade(@RequestBody CheckUpgradeDTO checkUpgradeDTO) {
        AppVersion appVersion =
                appVersionMapper.selectOne(
                        Wrappers.<AppVersion>lambdaQuery()
                                .eq(AppVersion::getAppType, checkUpgradeDTO.getAppType())
                                .eq(
                                        AppVersion::getVersionNumber,
                                        checkUpgradeDTO.getVersionNumber()));
        if (appVersion == null) {
            return new Result<>("版本号不存在", 500, null);
        }

        return new Result<>(appVersion);
    }
}
